
import Toast from '@vant/weapp/toast/toast';
import TIM from "tim-wx-sdk";
const recorderManager = wx.getRecorderManager();
const recordOptions = {
    duration: 58000, // 录音的时长，单位 ms，最大值 600000（10 分钟）
    sampleRate: 44100, // 采样率
    numberOfChannels: 1, // 录音通道数
    encodeBitRate: 192000, // 编码码率
    format: 'aac' // 音频格式，选择此格式创建的音频消息，可以在即时通信 IM 全平台（Android、iOS、微信小程序和Web）互通
};
let toast;

let startRecording = function(){
    wx.getSetting({
        success: (res) => {
          let auth = res.authSetting['scope.record']
          if (auth === false) { // 已申请过授权，但是用户拒绝
            wx.openSetting({
              success: function (res) {
                let auth = res.authSetting['scope.record']
                if (auth === true) {
                  wx.showToast({
                    title: '授权成功',
                    icon: 'success',
                    duration: 1500
                  })
                } else {
                  wx.showToast({
                    title: '授权失败',
                    icon: 'none',
                    duration: 1500
                  })
                }
              }
            })
          } else if (auth === true) { // 用户已经同意授权
            toast = Toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: false, // 禁用背景点击
                message: '正在录音',
                loadingType: 'spinner',
                selector: '#custom-selector',
                mask:false,
            });
            recorderManager.start(recordOptions);
          } else { // 第一次进来，未发起授权
            wx.authorize({
              scope: 'scope.record',
              success: () => {
                wx.showToast({
                  title: '授权成功',
                  icon: 'success',
                  duration: 1500
                })
              }
            })
          }
        },
        fail: function () {
          wx.showToast({
            title: '授权失败',
            icon: 'none',
            duration: 1500
          })
        }
      })
    
}

let handlerEvent = function(tim,userId, canSend, cb){
    // 2.1 监听录音错误事件
    recorderManager.onError(function(errMsg) {
        console.warn('recorder error:', errMsg);
        Toast({
            message: '发送失败,请重新发送',
            selector: '#custom-selector',
        });
    });
    // 2.2 监听录音结束事件，录音结束后，调用 createAudioMessage 创建音频消息实例
    recorderManager.onStop(function(res) {
        console.log('recorder stop', res);
        if(toast){
            toast.clear();
        }
        if(canSend){
            if (res.duration < 1000) {
                Toast({
                    message: '录音时间太短',
                    selector: '#custom-selector',
                });
            } else {
                // 4. 创建消息实例，接口返回的实例可以上屏
                const message = tim.createAudioMessage({
                    to: userId,
                    conversationType: TIM.TYPES.CONV_C2C,
                    // 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
                    // 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
                    // priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
                    payload: {
                        file: res
                    }
                });
                // 5. 发送消息
                let promise = tim.sendMessage(message);
                promise.then(function(imResponse) {
                    // 发送成功
                    console.log(imResponse);
                    cb(message);
                }).catch(function(imError) {
                    // 发送失败
                    console.warn('sendMessage error:', imError);
                });
            }
        }
    });
}

let playVoice = function (src) {
    let InnerAudioContext = wx.createInnerAudioContext();
    InnerAudioContext.src = src;
    InnerAudioContext.autoplay=true;
    InnerAudioContext.play();
    //开始监听
    InnerAudioContext.onPlay(() => {
        console.log('监听播放的回调函数')
    })
    //结束监听
    InnerAudioContext.onEnded(() => {
        console.log('end')
    })
    InnerAudioContext.onError((res) => {
        console.log(res.errMsg)
        console.log(res.errCode);
        Toast({
            message: '语音播放失败',
            selector: '#custom-selector',
        });
    })
}
module.exports = {
    startRecording: startRecording,
    handlerEvent:handlerEvent,
    playVoice:playVoice
}